import axios from "axios";
import apiResultCode from "@/components/api-result-code.js"
// import { Message } from "element-ui"

const service = axios.create({
  baseURL: process.env.API_URL,
  timeout: 60 * 1000,
});

// let errorcountlist = [];
// let timer = null;

// 请求拦截
service.interceptors.request.use(config => {
  // 数据转化,也可以使用qs转换
  config.data = JSON.stringify(config.data);
  config.headers = {
    'Content-Type': 'application/json;charset=utf-8', //配置请求头
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截。如果返回的Code为200，则直接返回；如果返回的Code长度为4，并且以3或4开头，则在打印错误消息后返回
service.interceptors.response.use(
  (res) => {
    if (res.data.Code !== apiResultCode.code.success) {
      let resultCode = res.data.Code.toString();
      if (resultCode.length == 4 && (resultCode.substring(0, 1) == "3" || resultCode.substring(0, 1) == "4")) {
        console.warn(res.data.Message);
        return res.data;
      } else {
        return Promise.reject(res.data);
      }
    } else {
      return res.data;
    }
  },
  (error) => {
    console.error(error)
    return Promise.reject(error)
  }
)

export default service;